package com.tcm.ucenter.service;

import cn.hutool.core.util.ObjectUtil;
import com.base.genid.generator.UidGenerator;
import com.tcm.ucenter.domain.entity.UserAccount;
import com.tcm.ucenter.domain.entity.UserAccountLog;
import com.tcm.ucenter.domain.enums.AccountSourceEnum;
import com.tcm.ucenter.domain.enums.AccountTypeEnum;
import com.tcm.ucenter.mapper.UserAccountLogMapper;
import com.tcm.ucenter.mapper.UserAccountMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class CoinChangeServiceImpl implements UserAccountChangeService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountLogMapper accountLogMapper;

    @DubboReference(version = "0.0.1-beta", group = "cached-uid", timeout = 6000, check = false, retries = 3)
    private UidGenerator uidGenerator;


    @Transactional
    @Override
    public void change(Long userId, Object quantity, String memo) {
        UserAccount uac = userAccountMapper.findByUserId(userId);
        Integer coin = (Integer) quantity;
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setUpdateTime(LocalDateTime.now());
        if (ObjectUtil.isEmpty(uac)) {
            userAccount.setId(uidGenerator.getUID());
            userAccount.setCoin(coin);
            userAccount.setCreateTime(LocalDateTime.now());
            userAccountMapper.insert(userAccount);
        } else {
            userAccount.setCoin(uac.getCoin() + coin);
            userAccountMapper.update(userAccount);
        }

        //新增日志
        UserAccountLog userAccountLog = new UserAccountLog();
        userAccountLog.setQuantity(String.valueOf(Math.abs(coin)));
        userAccountLog.setBalance(userAccount.getPoint().toString());
        userAccountLog.setDeleted(new Byte("0"));
        userAccountLog.setCreateTime(LocalDateTime.now());
        userAccountLog.setUpdateTime(LocalDateTime.now());
        if (coin > 0) {
            userAccountLog.setDirection(new Byte("1"));
        } else {
            userAccountLog.setDirection(new Byte("0"));
        }
        userAccountLog.setId(uidGenerator.getUID());
        userAccountLog.setSource(new Short(AccountSourceEnum.COIN.value()));
        userAccountLog.setUserId(userId);
        userAccountLog.setMemo(memo);
        accountLogMapper.insert(userAccountLog);
    }

    @Override
    public String supports() {
        return AccountTypeEnum.COIN.value();
    }


}

